package com.ky.pro.java.dt.app.service.impl;

import com.ky.pro.java.dt.app.proxy.KitchenProcessProxy;
import com.ky.pro.java.dt.app.proxy.OrderServiceProxy;
import com.ky.pro.java.dt.app.service.IPaymentPostProcessingService;
import com.ky.pro.java.dt.common.web.ResultBean;
import lombok.extern.slf4j.Slf4j;
import org.dromara.hmily.annotation.HmilyTCC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 完成支付后的操作：
 * 1. 更新订单状态
 * 2. 更新配餐状态
 */
@Service
@Slf4j
public class PaymentPostProcessingServiceImpl implements IPaymentPostProcessingService {

    OrderServiceProxy orderServiceProxy;

    KitchenProcessProxy kitchenProcessProxy;

    @Autowired
    public PaymentPostProcessingServiceImpl(OrderServiceProxy orderServiceProxy,
                                            KitchenProcessProxy kitchenProcessProxy) {
        this.orderServiceProxy = orderServiceProxy;
        this.kitchenProcessProxy = kitchenProcessProxy;
    }

    @Transactional
    @HmilyTCC(confirmMethod = "confirm", cancelMethod = "cancel")
    public void process(long orderNo) {
        ResultBean<Boolean> orderProcessResult =
                orderServiceProxy.checkExistence(orderNo);
        if (!orderProcessResult.isSuccess() || !orderProcessResult.getData()) {
            throw new RuntimeException("订单检查失败！");
        }
        ResultBean<Boolean> kitchenProcessResult =
                kitchenProcessProxy.checkExistence(orderNo);
        if (!kitchenProcessResult.isSuccess() || !kitchenProcessResult.getData()) {
            throw new RuntimeException("配餐记录检查失败！");
        }
        log.info("订单、配餐记录检查成功");
    }

    @Transactional
    public void confirm(long orderNo) {
        // TODO: 幂等处理
        log.info("开始执行支付后处理操作...");
        ResultBean<String> orderProcessResult =
                orderServiceProxy.updateOrderStatus(orderNo, 1);
        if (!orderProcessResult.isSuccess()) {
            throw new RuntimeException("订单状态更新失败！");
        }
        ResultBean<String> kitchenProcessResult =
                kitchenProcessProxy.updateKitchenProcessStatus(orderNo, 1);
        if (!kitchenProcessResult.isSuccess()) {
            throw new RuntimeException("配餐状态更新失败！");
        }
        log.info("支付后操作完成！");
    }

    @Transactional
    public void cancel(long orderNo) {
        log.info("开始回滚操作...");
        ResultBean<String> orderProcessResult =
                orderServiceProxy.updateOrderStatus(orderNo, 0);
        if (!orderProcessResult.isSuccess()) {
            log.error("订单状态更新失败！");
        }
        ResultBean<String> kitchenProcessResult =
                kitchenProcessProxy.updateKitchenProcessStatus(orderNo, 0);
        if (!kitchenProcessResult.isSuccess()) {
            log.error("配餐状态更新失败！");
        }
        log.info("回滚操作完成！");
    }

}
